<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getBusinessPoolListApi, getBusinessDetailApi } from '@/api/business'

const router = useRouter()

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 搜索条件
const searchForm = reactive({
  businessId: '',
  name: '',
  phone: '',
  subject: ''
})

// 公海池列表数据
const poolList = ref([])

// 加载状态
const loading = ref(false)

// 科目选项
const subjectOptions = [
  { label: '语文', value: 1 },
  { label: '数学', value: 2 },
  { label: '英语', value: 3 },
  { label: '物理', value: 4 },
  { label: '化学', value: 5 },
  { label: '生物', value: 6 },
  { label: 'UI设计', value: 9 },
  { label: '其他', value: 7 }
]

// 性别选项
const genderOptions = [
  { label: '男', value: 1 },
  { label: '女', value: 2 }
]

// 渠道选项
const channelOptions = [
  { label: '电话', value: 1 },
  { label: '线上', value: 2 },
  { label: '推荐', value: 3 },
  { label: '其他', value: 4 }
]

// 学历选项
const degreeOptions = [
  { label: '小学', value: 1 },
  { label: '初中', value: 2 },
  { label: '高中', value: 3 },
  { label: '本科', value: 4 },
  { label: '硕士', value: 5 },
  { label: '博士', value: 6 },
  { label: '其他', value: 7 }
]

// 工作状态选项
const jobStatusOptions = [
  { label: '在职', value: 1 },
  { label: '离职', value: 2 },
  { label: '学生', value: 3 },
  { label: '其他', value: 4 }
]

// 加载公海池列表
const loadPoolList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    
    // 过滤掉空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const result = await getBusinessPoolListApi(params)
    
    if (result.code === 1) {
      poolList.value = result.data.rows || []
      pagination.total = result.data.total || 0
    } else {
      ElMessage.error(result.msg || '获取公海池列表失败')
    }
  } catch (error) {
    console.error('获取公海池列表出错:', error)
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadPoolList()
}

// 重置搜索条件
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.currentPage = 1
  loadPoolList()
}

// 分页变化
const handlePageChange = (currentPage) => {
  pagination.currentPage = currentPage
  loadPoolList()
}

// 每页条数变化
const handleSizeChange = (pageSize) => {
  pagination.pageSize = pageSize
  loadPoolList()
}

// 获取科目名称
const getSubjectName = (subjectId) => {
  const option = subjectOptions.find(opt => opt.value === subjectId)
  return option ? option.label : '未知'
}

// 获取性别标签
const getGenderLabel = (gender) => {
  const option = genderOptions.find(opt => opt.value === gender)
  return option ? option.label : '未知'
}

// 获取渠道标签
const getChannelLabel = (channel) => {
  const option = channelOptions.find(opt => opt.value === channel)
  return option ? option.label : '未知'
}

// 获取学历标签
const getDegreeLabel = (degree) => {
  const option = degreeOptions.find(opt => opt.value === degree)
  return option ? option.label : '未知'
}

// 获取工作状态标签
const getJobStatusLabel = (jobStatus) => {
  const option = jobStatusOptions.find(opt => opt.value === jobStatus)
  return option ? option.label : '未知'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 查看商机详情
const handleViewBusiness = async (id) => {
  try {
    const result = await getBusinessDetailApi(id)
    if (result.code === 1) {
      // 可以将详情数据存储到全局状态或通过路由参数传递
      router.push(`/business/detail/${id}`)
    } else {
      ElMessage.error(result.msg || '查询商机详情失败')
    }
  } catch (error) {
    console.error('查询商机详情出错:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadPoolList()
})
</script>

<template>
  <div class="business-pool">
    <h2 class="page-title">商机公海池</h2>
    
    <!-- 搜索条件区域 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商机ID">
          <el-input v-model="searchForm.businessId" placeholder="请输入商机ID" />
        </el-form-item>
        
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入客户姓名" />
        </el-form-item>
        
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        
        <el-form-item label="科目">
          <el-select v-model="searchForm.subject" placeholder="请选择科目">
            <el-option v-for="option in subjectOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 数据表格 -->
    <div class="table-section">
      <el-table 
        v-loading="loading" 
        :data="poolList" 
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="商机ID" width="80" />
        <el-table-column prop="name" label="客户姓名" width="100" />
        <el-table-column prop="phone" label="手机号" width="150" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            {{ getGenderLabel(scope.row.gender) }}
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column prop="subject" label="科目" width="100">
          <template #default="scope">
            {{ getSubjectName(scope.row.subject) }}
          </template>
        </el-table-column>
        <el-table-column prop="channel" label="渠道" width="100">
          <template #default="scope">
            {{ getChannelLabel(scope.row.channel) }}
          </template>
        </el-table-column>
        <el-table-column prop="degree" label="学历" width="100">
          <template #default="scope">
            {{ getDegreeLabel(scope.row.degree) }}
          </template>
        </el-table-column>
        <el-table-column prop="jobStatus" label="工作状态" width="100">
          <template #default="scope">
            {{ getJobStatusLabel(scope.row.jobStatus) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" />
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleViewBusiness(scope.row.id)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.business-pool {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.search-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-form {
  display: flex;
  align-items: end;
  gap: 15px;
}

.table-section {
  margin-top: 20px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form {
    flex-wrap: wrap;
  }
}

@media (max-width: 768px) {
  .business-pool {
    padding: 10px;
  }
  
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form .el-form-item {
    margin-bottom: 15px;
  }
}
</style>
